class Kingdom < ActiveRecord::Base
  validates_presence_of :name
  belongs_to  :culture
  has_many    :duchies
  
  def Kingdom.realm_choice(realm)
    return nil unless realm
    realm_array = realm.split(":")
    territory = nil
    if realm_array
      if realm_array[0] == "kingdom"
        territory = Kingdom.find(realm_array[1])
      elsif realm_array[0] == "duchy"
        territory = Duchy.find(realm_array[1])
      elsif realm_array[0] == "county"
        territory = County.find(realm_array[1])
      elsif realm_array[0] == "town"
        territory = Town.find(realm_array[1])
      end
    end
    return territory
  end
  
  def Kingdom.random
    kingdoms = Kingdom.find(:all)
    if kingdoms
      return kingdoms[rand(kingdoms.size)]
    end
  end
  
  def Kingdom.with_ruler(character)
    return nil unless character
    kingdoms = Kingdom.find(:all)
    for kingdom in kingdoms
      ruler = kingdom.ruler
      return kingdom unless ruler.nil? or ruler.id != character.id
    end
    return nil
  end
  
  def ruler
    Title.king_of self
  end
end
